from fdlite import FaceDetection, FaceLandmark, face_detection_to_roi
from fdlite import IrisLandmark, iris_roi_from_face_landmarks
from fdlite.examples.iris_recoloring import recolor_iris
from PIL import Image

class iris_distance(object):
    def __init__(self):
        """初始化"""
        self.detect_faces = FaceDetection()
        self.detect_face_landmarks = FaceLandmark()
        self.detect_iris = IrisLandmark()
        self.EXCITING_NEW_EYE_COLOR = (161, 52, 216)
    def face_detection(self,image):
        '''根据输入图片检测人脸，返回结果'''
        face_detections = self.detect_faces(image)
        return face_detections
    def iris_detection(self,image):
        """对输入图片检测人脸虹膜"""
        # get ROI for the first face found
        face_detections=self.face_detection(image)
        face_roi = face_detection_to_roi(face_detections[0], img.size)
        # detect face landmarks
        face_landmarks = detect_face_landmarks(img, face_roi)
        # get ROI for both eyes
        eye_roi = iris_roi_from_face_landmarks(face_landmarks, img.size)
        left_eye_roi, right_eye_roi = eye_roi
        # detect iris landmarks for both eyes
        left_eye_results = detect_iris(img, left_eye_roi)
        right_eye_results = detect_iris(img, right_eye_roi, is_right_eye=True)
        return
    def draw_iris(self,image,left_eye_results,right_eye_results):
        recolor_iris(image, left_eye_results, iris_color=self.EXCITING_NEW_EYE_COLOR)
        recolor_iris(image, right_eye_results, iris_color=self.EXCITING_NEW_EYE_COLOR)
    def process(self,image):
        '''输入image，输出虹膜测距'''


EXCITING_NEW_EYE_COLOR = (161, 52, 216)
# load detection models
detect_faces = FaceDetection()
detect_face_landmarks = FaceLandmark()
detect_iris = IrisLandmark()

# open image
img = Image.open('docs/portrait_exif.jpg')
# detect face
face_detections = detect_faces(img)
if len(face_detections):
    # get ROI for the first face found
    face_roi = face_detection_to_roi(face_detections[0], img.size)
    # detect face landmarks
    face_landmarks = detect_face_landmarks(img, face_roi)
    # get ROI for both eyes
    eye_roi = iris_roi_from_face_landmarks(face_landmarks, img.size)
    left_eye_roi, right_eye_roi = eye_roi
    # detect iris landmarks for both eyes
    left_eye_results = detect_iris(img, left_eye_roi)
    right_eye_results = detect_iris(img, right_eye_roi, is_right_eye=True)
    # change the iris color
    recolor_iris(img, left_eye_results, iris_color=EXCITING_NEW_EYE_COLOR)
    recolor_iris(img, right_eye_results, iris_color=EXCITING_NEW_EYE_COLOR)
    img.show()
else:
    print('no face detected :(')